<script setup lang="ts">
import { onMounted } from 'vue'
import { ref } from 'vue'
import { bindMobile, loginByQQ } from '@/services/user'
import { mobileRules, codeRules } from '@/utils/rules'
import { useSendMobileCode } from '@/composable'
import type { User } from '@/types/user'
import { useUserStore } from '@/stores'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'

// 1. 调用登录接口
const openId = ref('') // 用户唯一标识
const isNeedBind = ref(false) // 是否需要绑定手机号
onMounted(() => {
  if (window.QC.Login.check()) {
    // qq登录回跳过来的
    window.QC.Login.getMe((id: string) => {
      openId.value = id
      loginByQQ(openId.value)
        .then((res) => {
          console.log('-----+++来了')
          // 登录成功进入(QQ已经绑定了手机号)
          loginSuccess(res.data)
        })
        .catch(() => {
          // 登录失败(QQ没有绑定手机号)
          isNeedBind.value = true
        })
    })
  }
})

// 2. 发送短信验证码
const mobile = ref('')
const code = ref('')
const { formRef, send, time } = useSendMobileCode(mobile, 'bindMobile')

const bind = async () => {
  const res = await bindMobile({
    mobile: mobile.value,
    code: code.value,
    openId: openId.value
  })
  // 拿到用户信息之后的处理
  loginSuccess(res.data)
}

const store = useUserStore()
const router = useRouter()
const loginSuccess = (user: User) => {
  // 把用户信息存储到仓库
  store.setUser(user)
  // 提示登录成功
  showToast('登录成功')
  // 跳转到我的
  router.push(store.returnUrl || '/user')
  // 清空returnUrl
  store.setReturnUrl('')
}
</script>

<template>
  <div class="login-page" v-if="isNeedBind">
    <cp-nav-bar></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="formRef" @submit="bind">
      <van-field
        name="mobile"
        v-model="mobile"
        placeholder="请输入手机号"
        type="tel"
        :rules="mobileRules"
      ></van-field>
      <van-field
        v-model="code"
        placeholder="请输入短信验证码"
        :rules="codeRules"
      >
        <!-- 自定义输入框尾部按钮 -->
        <template #button>
          <span class="btn-send" :class="{ active: time > 0 }" @click="send">
            {{ time > 0 ? `${time}s后重新获取` : '发送验证码' }}
          </span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button
          style="margin-top: 50px"
          block
          round
          type="primary"
          native-type="submit"
        >
          立即绑定
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>
